package cn.lbd.api.designMode.strategy.factory;

import cn.lbd.api.designMode.strategy.entity.PriceRegion;
import cn.lbd.api.designMode.strategy.entity.Member;
import cn.lbd.api.designMode.strategy.entity.Ordinary;
import cn.lbd.api.designMode.strategy.entity.Price;
import cn.lbd.api.designMode.strategy.entity.SuperMember;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class PriceFactory {
    private static final PriceFactory FACTORY = new PriceFactory();

    //策略集合
    private List<Class<? extends Price>> priceList = new ArrayList<>();

    //构造方法初始化时导入策略类
    private PriceFactory() {
        priceList.add(Member.class);
        priceList.add(SuperMember.class);
        priceList.add(Ordinary.class);
    }

    //如何选择策略
    public Price getPrice(BigDecimal price) throws IllegalAccessException, InstantiationException {
        for (Class<? extends Price> clazz : priceList) {
            PriceRegion priceRegion = clazz.getAnnotation(PriceRegion.class);
            //判断传入的金额在不在当前策略金额的区间之类，是的话返回，如果都找不到就返回空
            if (price.compareTo(new BigDecimal(priceRegion.max())) < 0 && price.compareTo(new BigDecimal(priceRegion.min())) > 0) {
                return clazz.newInstance();
            }
        }
        return null;
    }

    //单例模式，静态构造器的缘故，只能通过该静态方法去拿到工厂
    public static PriceFactory getFactory() {
        return FACTORY;
    }
}
